#include <iostream>
#include <grpcpp/grpcpp.h>
#include <memory>
#include <string>
#include "include/user_service.grpc.pb.h"
#include "include/user_service.pb.h"
#include "include/UserServiceImpl.h"
#include "include/UserContainer.h"
#include <thread>
#include <condition_variable>
#include <mutex>
#include <signal.h>


bool b_stop=false;
std::condition_variable cv;
std::mutex mtx;
void SignalHandler(int signum)
{
    std::unique_lock<std::mutex> lck(mtx);
    b_stop=true;
    cv.notify_one();
}


void RunServer()
{
    std::string server_addr("0.0.0.0:50051");
    UserServiceImpl user_service_impl;
    ::grpc::ServerBuilder builder;
    //添加监听端口
    builder.AddListeningPort(server_addr, ::grpc::InsecureServerCredentials());
    //注册服务
    builder.RegisterService(&user_service_impl);

    std::unique_ptr<::grpc::Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_addr << std::endl;
    
    std::thread stop_thread([&](){
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock,[&](){return b_stop;});
        //关闭服务器
        server->Shutdown();
    });
    
    server->Wait();
    stop_thread.join();
    std::cout<<"Server stopped"<<std::endl;

}


int main(){

    signal(SIGINT,SignalHandler);
    signal(SIGTERM,SignalHandler);

    RunServer();
    return 0;
}

